package cn.wolfcode.shop.schedule.task;

import cn.wolfcode.shop.domain.Catalog;
import cn.wolfcode.shop.service.ICatalogService;
import cn.wolfcode.shop.service.IPropertyService;
import cn.wolfcode.shop.util.RedisConstants;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 *  定时器
 */
@Component
public class ScheduleTask {
    @Reference
    private IPropertyService propertyService;
    @Reference
    private ICatalogService catalogService;
    @Autowired
    private RedisTemplate redisTemplate;


    /**
     * 定时更新商品分类属性个数的redis缓存值
     * 每天凌晨的时候执行一次
     */
    @Scheduled(cron = "0 0 0 * * ?")
    public void updateCatalogPropertyNum(){
        //查询所有商品分类
        List<Catalog> catalogs = catalogService.listAll();
        catalogs.forEach(catalog -> {
            Integer count=propertyService.selectForCountByCatalogId(catalog.getId());
            redisTemplate.opsForValue().set(RedisConstants.CATALOG_PROPERTYS_COUNT
                    .replace("CATALOG_ID",catalog.getId().toString()),count);
        });
    }

}
